package cn.yi.newsys.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.yi.newsys.pojo.PageBean;
import cn.yi.newsys.pojo.User;
import cn.yi.newsys.service.UserService;
import cn.yi.newsys.service.impl.UserServiceImpl;

public class SearchUserServlet extends HttpServlet {


	private static final long serialVersionUID = 1L;


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response) ;
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		// 设置请求的编码格式
		request.setCharacterEncoding("UTF-8") ;
		
		// 用户身份标记
		int roleId = -1 ;
		// 从请求数据中获取用户查询关键字
		String queryName = request.getParameter("queryUserName") ;
		// 从请求数据中获取用户查询身份
		String userType = request.getParameter("queryUserType") ;
		if(userType != null && userType.length() > 0){
			roleId = Integer.valueOf(userType) ;
		}
		// 设置当前页面为 1 
		int currentPageNo = 1 ;
		// 设置每页显示 10 条数据
		int pageSize = 10 ;
		// 创建用户业务逻辑对象
		UserService us = new UserServiceImpl() ;
		// 获取总页数
		int totalPage = us.getTotalPage(pageSize, queryName, roleId) ;
		if(totalPage > 0){
			// 获取用户请求中的页码标记
			String pageNo = request.getParameter("pageno") ;
			if(pageNo != null && pageNo.length() > 0){
				currentPageNo = Integer.valueOf(pageNo) ;
			}
			// 设置页码最小值
			if(currentPageNo <= 0){
				currentPageNo = 1 ;
			}
			// 设置页码最大值
			if(currentPageNo >= totalPage){
				currentPageNo = totalPage ;
			}
			// 获取 pageBean 
			PageBean<User> pb = us.queryUserByPageNo(currentPageNo, pageSize, queryName, roleId) ;
			// 获取 session 对象
			HttpSession session = request.getSession() ;
			// 保存 pageBean 到 session 中
			session.setAttribute("bean", pb) ;
			// 保存查询关键词到 session 中
			session.setAttribute("queryName",queryName) ;
			// 保存查询用户类型到 session 中
			session.setAttribute("roleId", roleId) ;
			// 重定向页面回到用户列表页面
			response.sendRedirect("userlist.jsp") ;
		}else{
			out.println("<script>alert('未查询到数据');</script>") ;
		}
		out.flush();
		out.close();
	}

}
